package com.example.amarsoft.coolweatherwk.util;

import android.text.TextUtils;

import com.example.amarsoft.coolweatherwk.db.City;
import com.example.amarsoft.coolweatherwk.db.County;
import com.example.amarsoft.coolweatherwk.db.Province;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by amarsoft on 2017/8/7.
 */

public class Utility {
    /**
     * 解析返回的JSON省级数据
     */
    public static boolean handleProvinceResponse (String respone) {

        if (!TextUtils.isEmpty(respone)) {
            try {
                JSONArray allProvinces = new JSONArray(respone);
                for (int i = 0; i < allProvinces.length(); i++) {
                    JSONObject provinceObject = allProvinces.getJSONObject(i);
                    Province province = new Province();
                    province.setProvinceName(provinceObject.getString("name"));
                    province.setProvinceCode(provinceObject.getInt("id"));
                    province.save();
                }
                return true;
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
        return false;
    }
    /**
     * 解析返回的JSON市级数据
     */
    public static boolean handleCityResponse (String respone, int provinceId) {

        if (!TextUtils.isEmpty(respone)) {
            try {
                JSONArray allCitys = new JSONArray(respone);
                for (int i = 0; i < allCitys.length(); i++) {
                    JSONObject cityObject = allCitys.getJSONObject(i);
                    City city = new City();
                    city.setCityCode(cityObject.getInt("id"));
                    city.setCityName(cityObject.getString("name"));
                    city.setProvinceId(provinceId);
                    city.save();
                }
                return true;
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
        return false;
    }
    /**
     * 解析返回的JSON县级数据
     */
    public static boolean handleCountyResponse (String respone, int cityId) {

        if (!TextUtils.isEmpty(respone)) {
            try {
                JSONArray allCountys = new JSONArray(respone);
                for (int i = 0; i < allCountys.length(); i++) {
                    JSONObject countyObject = allCountys.getJSONObject(i);
                    County county = new County();
                    county.setCityId(cityId);
                    county.setCountyName(countyObject.getString("name"));
                    county.setWeatherId(countyObject.getString("weather_id"));
                    county.save();
                }
                return true;
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
        return false;
    }
}
